<template>
  <div class="pConfig page-miH page-bgBack">
    <PageHeader @back="$router.go(-1)" subTitle="返回"> 配置 </PageHeader>
    <a-tabs
      style="margin-top: 24px"
      class="tabs"
      :tab-bar-style="{ width: '214px' }"
      tab-position="left"
      default-active-key="1"
      @change="tabChange"
    >
      <a-tab-pane key="1" tab="权限配置">
        <div style="display: flex; justify-content: space-between; align-items: center">
          <a-select v-model="roleId" style="width: 200px" @change="selectChange">
            <a-select-option v-for="item in roleOptions" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
          <a-button type="primary" @click="savePermission">保存</a-button>
        </div>
        <a-spin :spinning="loading">
          <a-tabs type="card" @change="onSubjectChange" style="margin-top: 24px" size="small">
            <a-tab-pane key="company" tab="操作端">
              <div class="titleBox"><a-checkbox @change="checkAll" v-model="checkAllState" style="margin: 0 12px 0 12px" /> 员工端权限</div>
              <div class="childBox" v-for="item in treeData" :key="item.id">
                <div style="width: 200px; height: 18px; border-right: 1px solid #e8e8e8">
                  <a-checkbox
                    :disabled="!item.children || item.children.length === 0"
                    style="margin: 0 12px 0 12px"
                    v-model="item.checked"
                    @change="checkGroup(item)"
                  />
                  {{ item.categoryName }}
                </div>
                <div style="flex: 1; display: flex; flex-wrap: wrap">
                  <div v-for="item2 in item.children" :key="item2.id">
                    <a-checkbox style="margin: 0 12px 0 24px" v-model="item2.checked" @change="checkItem(item2)" /> {{ item2.name }}
                  </div>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="hr" tab="管理端">
              <div class="titleBox"><a-checkbox @change="checkAll" v-model="checkAllState" style="margin: 0 12px 0 12px" /> 管理端权限</div>
              <div class="childBox" v-for="item in treeData" :key="item.id">
                <div style="width: 200px; height: 18px; border-right: 1px solid #e8e8e8">
                  <a-checkbox style="margin: 0 12px 0 12px" v-model="item.checked" @change="checkGroup(item)" /> {{ item.categoryName }}
                </div>
                <div style="flex: 1; display: flex; flex-wrap: wrap">
                  <template v-for="item2 in item.children">
                    <div v-if="showBox(item2)" :key="item2.id">
                      <a-checkbox style="margin: 0 12px 0 24px" v-model="item2.checked" @change="checkItem(item2)" /> {{ item2.name }}
                    </div>
                  </template>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="addedServices" tab="拓展应用">
              <a-table
                v-if="subjectType === 'addedServices' && treeData.length"
                rowKey="id"
                :columns="columns"
                :data-source="treeData"
                :pagination="false"
                childrenColumnName="childList"
              >
                <div
                  slot="categoryName"
                  slot-scope="text, record"
                  style="display: flex; align-items: center; margin-left: 35px; margin-bottom: 18px"
                  :class="!record.serviceIcon ? 'noIcon' : null"
                >
                  <div v-if="record.serviceIcon && record.serviceIcon.length">
                    <img :src="record.serviceIcon[0]" style="width: 30px; height: 30px; margin-left: 12px; margin-right: 12px" />
                  </div>
                  {{ text }}
                </div>
                <div slot="permissionList" slot-scope="text" style="display: flex">
                  <template v-for="(item, index) in text">
                    <div :key="`${item.enName}_${index}`">
                      <a-checkbox style="margin: 0 12px 0 24px" v-model="item.checked">{{ item.name }}</a-checkbox>
                    </div>
                  </template>
                </div>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="xcxAdmin" tab="小程序管理端">
              <a-table
                v-if="subjectType === 'xcxAdmin' && treeData.length"
                rowKey="id"
                :columns="columns"
                :data-source="treeData"
                :pagination="false"
                childrenColumnName="childList"
              >
                <div slot="categoryName" slot-scope="text" style="display: flex; align-items: center; margin-left: 35px">
                  {{ text }}
                </div>
                <div slot="permissionList" slot-scope="text" style="display: flex; flex-wrap: wrap">
                  <template v-for="(item, index) in text">
                    <div :key="item.enName + index">
                      <a-checkbox style="margin: 0 12px 0 24px" v-model="item.checked">{{ item.name }}</a-checkbox>
                    </div>
                  </template>
                </div>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="xcxJiafang" tab="小程序甲方端">
              <a-table
                v-if="subjectType === 'xcxJiafang' && treeData.length"
                rowKey="id"
                :columns="columns"
                :data-source="treeData"
                :pagination="false"
                childrenColumnName="childList"
              >
                <div slot="categoryName" slot-scope="text" style="display: flex; align-items: center; margin-left: 35px">
                  {{ text }}
                </div>
                <div slot="permissionList" slot-scope="text" style="display: flex; flex-wrap: wrap">
                  <template v-for="(item, index) in text">
                    <div :key="item.enName + index" style="display: flex">
                      <a-checkbox style="margin: 0 12px 0 24px" v-model="item.checked">{{ item.name }}</a-checkbox>
                    </div>
                  </template>
                </div>
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </a-spin>
      </a-tab-pane>
      <a-tab-pane key="2" tab="角色信息">
        <a-select v-model="roleId" style="width: 200px" @change="selectInfo">
          <a-select-option v-for="item in roleOptions" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
        </a-select>
        <a-form-item label="角色名称" label-align="left">
          <a-input v-model="roleName" style="width: 200px" placeholder="请输入角色" allow-clear />
        </a-form-item>
        <a-form-item label="角色描述" label-align="left">
          <a-input v-model="roleIntro" style="width: 200px" placeholder="请输入描述" allow-clear />
        </a-form-item>
        <a-button type="primary" @click="updateRole">更新角色设置</a-button>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import { getRoleList, updateRoleSetting, roleDetailById, saveRoleRight, checkRoleRights, getServiceOpens } from "@/api/company/member";
const columns = [
  {
    title: "增值服务",
    dataIndex: "categoryName",
    key: "categoryName",
    width: 220,
    scopedSlots: { customRender: "categoryName" }
  },
  {
    title: "权限配置",
    dataIndex: "permissionList",
    key: "permissionList",
    scopedSlots: { customRender: "permissionList" }
  }
];
export default {
  data() {
    return {
      columns,
      actionId: this.$route.query.actionId,
      hrId: this.$route.query.hrId,
      replaceFields: {
        children: "childList",
        key: "categoryId",
        value: "categoryId",
        title: "categoryName"
      },
      loading: false,
      checkAllState: false,
      permission: {},
      checkedKeys: [],
      treeData: [],
      subjectType: "company",
      roleInfos: "",
      roleIntro: "",
      roleId: this.$route.query.id,
      roleName: "",
      saveArr: [],
      ServiceDataList: [],
      dto: [],
      roleType: "",
      type: [
        {
          value: "A",
          label: "管理员"
        },
        {
          value: "U",
          label: "普通成员"
        }
      ],
      roleOptions: [],
      permissionIds: []
    };
  },
  created() {
    // 获取详情列表
    this.getRoleDetail(this.roleId);
    // 获取权限列表
    this.permissionList();
  },
  methods: {
    getServiceOpens() {
      getServiceOpens().then((res) => {
        this.ServiceDataList = res.data;
      });
    },
    onSelect(selectedKeys, info) {
      console.log("selected", selectedKeys, info);
    },
    onCheck(checkedKeys, info) {
      console.log("onCheck", checkedKeys, info);
    },
    showBox(item) {
      if (["guanwangxinwen", "kaowubaoming"].includes(item.enName)) {
        if (window.location.host.includes("csxr.cn")) {
          return true;
        }
        return false;
      }
      return true;
    },
    checkItem(e) {
      let isAllGroup = 0;
      this.treeData.forEach((item) => {
        if (item.checked === false) {
          this.checkAllState = false;
        }
        if (item.children) {
          let isAll = 0;
          item.children.forEach((item2) => {
            if (item2.checked === true) {
              isAll = isAll + 1;
            }
            if (item2.checked === false) {
              item.checked = false;
              this.checkAllState = false;
            }
            if (isAll === item.children.length) {
              item.checked = true;
              isAllGroup = isAllGroup + 1;
            }
          });
        } else {
          isAllGroup = isAllGroup + 1;
        }
      });
      if (isAllGroup === this.treeData.length) {
        this.checkAllState = true;
      } else {
        this.checkAllState = false;
      }
      this.treeData = JSON.parse(JSON.stringify(this.treeData));
    },
    checkAll(e) {
      if (e.target.checked) {
        this.checkAllState = true;
        this.treeData.forEach((item) => {
          item.checked = true;
          if (item.children) {
            item.children.forEach((item2) => {
              item2.checked = true;
            });
          }
        });
      } else {
        this.checkAllState = false;
        this.treeData.forEach((item) => {
          item.checked = false;
          if (item.children) {
            item.children.forEach((item2) => {
              item2.checked = false;
            });
          }
        });
      }
      this.treeData = JSON.parse(JSON.stringify(this.treeData));
    },
    checkGroup(e) {
      let isAll = 0;
      this.treeData.forEach((item, index) => {
        if (item.checked === true) {
          isAll = isAll + 1;
        } else {
          this.checkAllState = false;
        }
      });
      if (isAll === this.treeData.length) {
        this.checkAllState = true;
      }
      if (e.checked) {
        if (e.children) {
          e.children.forEach((item) => {
            item.checked = true;
          });
        }
      } else {
        this.checkAllState = false;
        if (e.children) {
          e.children.forEach((item) => {
            item.checked = false;
          });
        }
      }
    },
    onSubjectChange(key) {
      this.treeData = [];
      this.subjectType = key;
      this.columns[0].title =
        {
          addedServices: "增值服务",
          xcxAdmin: "小程序管理端权限",
          xcxJiafang: "小程序甲方端权限"
        }[key] || "";
      if (key === "addedServices") {
        getServiceOpens().then((res) => {
          this.ServiceDataList = res.data;
          this.ServiceDataList.forEach((item, index) => {
            if (!item.openStatus) {
              this.ServiceDataList.splice(index, 1);
            }
          });
          var arr = [];
          if (this.ServiceDataList && this.ServiceDataList.length) {
            this.ServiceDataList.forEach((item, index) => {
              item.childList = [];
              if (item.serviceIcon) {
                item.serviceIcon = item.serviceIcon.split(",");
              }
              if (item.openStatus) {
                this.loading = true;
                checkRoleRights({
                  roleId: this.subjectType === "company" ? this.actionId : this.hrId,
                  subjectType: item.serviceCode
                })
                  .then(({ data }) => {
                    if (data && data.length) {
                      arr = arr.concat(data);
                    }
                    this.treeData = JSON.parse(JSON.stringify(arr));
                    this.buildData();
                    this.loading = false;
                  })
                  .catch((err) => {
                    this.loading = false;
                    console.log("debug log --> ", err);
                    throw new Error("err", err);
                  });
              }
            });
          }
        });
      } else {
        this.permissionList();
      }
    },
    buildData() {
      this.ServiceDataList.forEach((item, index) => {
        item.categoryName = item.serviceName;
        this.treeData.forEach((item2, index2) => {
          if (item2.subjectType === item.serviceCode) {
            item.childList.push(item2);
          }
        });
      });
      this.treeData = JSON.parse(JSON.stringify(this.ServiceDataList));
      this.treeData.forEach((item) => {
        if (!item.childList || !item.childList.length) {
          item.childList = undefined;
        } else {
          item.childList = this.unique(item.childList);
        }
      });
    },
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.categoryId) && res.set(arr.categoryId, 1));
    },
    tabChange(e) {
      this.getRoleDetail(this.roleId);
    },
    // 获取角色信息-------------
    selectInfo(id) {
      const item = this.roleOptions.find((i) => i.id === id);
      this.roleName = item.name;
      this.roleIntro = item.description;
      this.roleType = item.valid;
      this.roleId = item.id;
      this.getRoleDetail(this.roleId);
    },
    // 更新角色配置------
    updateRole() {
      if (!this.roleName) {
        this.$notification["error"]({
          message: "Error",
          description: "角色名称不能为空"
        });
        return;
      }
      var updateRoleDTO = {
        description: this.roleIntro,
        name: this.roleName,
        id: this.roleId,
        type: "U"
      };
      updateRoleSetting(updateRoleDTO)
        .then((res) => {
          if (res.success) {
            this.getRoleDetail(this.roleId);
            this.$notification["success"]({
              message: "更新角色信息成功",
              description: res.msg
            });
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          throw new Error(err);
        });
    },
    // 保存权限-----
    arrSave(data) {
      data.forEach((item, index) => {
        if (item.permissionList) {
          this.saveArr = this.saveArr.concat(item.permissionList);
          item.permissionList.forEach((item2) => {
            item2.subjectType = item.subjectType;
          });
        }
        if (item.childList && item.childList.length) {
          this.arrSave(item.childList);
        }
      });
    },

    savePermission() {
      if (this.subjectType === "addedServices") {
        this.saveArr = [];
        var treeDataCopy = [];
        this.treeData.forEach((item) => {
          if (item.childList && item.childList.length) {
            treeDataCopy.push(item);
          }
        });
        this.arrSave(treeDataCopy);
        const dataArr = [];
        this.saveArr.map((mapItem) => {
          if (dataArr.length === 0) {
            dataArr.push({ subjectType: mapItem.subjectType, List: [mapItem] });
          } else {
            const res = dataArr.some((item) => {
              // 判断相同屬性，有就添加到当前项
              if (item.subjectType === mapItem.subjectType) {
                item.List.push(mapItem);
                return true;
              }
            });
            if (!res) {
              // 如果没找相同屬性添加一个新对象
              dataArr.push({ subjectType: mapItem.subjectType, List: [mapItem] });
            }
          }
        });
        this.dto = [];
        dataArr.forEach((item) => {
          var arr = [];
          if (item.List && item.List.length) {
            item.List.forEach((item2) => {
              if (item2.checked) {
                arr.push(item2.permissionId);
              }
            });
            this.dto.push({
              permissionIds: arr.toString(),
              subjectIds: "0",
              roleId: this.subjectType === "company" ? this.actionId : this.hrId,
              subjectType: item.subjectType
            });
          }
        });
      } else {
        this.treeData.forEach((item, index) => {
          // if (item.checked === true) {
          //   this.checkedKeys.push(item.categoryId);
          // }
          if (["xcxAdmin", "xcxJiafang"].includes(this.subjectType)) {
            item.permissionList.forEach((item2, index2) => {
              if (item2.checked === true) {
                this.checkedKeys.push(item2.permissionId);
              }
            });
          } else if (item.children) {
            item.children.forEach((item2, index2) => {
              if (item2.checked === true) {
                this.checkedKeys.push(item2.permissionId);
              }
            });
          }
        });

        this.dto = [];
        this.dto.push({
          permissionIds: this.checkedKeys.toString(),
          subjectIds: "0",
          roleId: this.subjectType === "company" ? this.actionId : this.hrId,
          subjectType: this.subjectType
        });
      }

      saveRoleRight(this.dto)
        .then((res) => {
          if (res.success) {
            // 获取权限列表
            if (this.subjectType === "addedServices") {
              this.onSubjectChange("addedServices");
            } else {
              this.permissionList();
            }

            this.$notification["success"]({
              message: "权限配置成功",
              description: res.msg
            });
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          throw new Error(err);
        });
    },
    // 获取权限列表
    permissionList(e) {
      this.loading = true;
      this.checkedKeys = [];
      checkRoleRights({
        roleId: this.subjectType === "company" ? this.actionId : this.hrId,
        subjectType: e || this.subjectType
      })
        .then(({ data }) => {
          this.treeData = this.dataDeep(data);
          let isAllGroup = 0;
          this.treeData.forEach((item) => {
            if (item.checked === false) {
              this.checkAllState = false;
            }
            if (item.children) {
              let isAll = 0;
              item.children.forEach((item2) => {
                if (item2.checked === true) {
                  isAll = isAll + 1;
                }
                if (item2.checked === false) {
                  item.checked = false;
                  this.checkAllState = false;
                }
                if (isAll === item.children.length) {
                  item.checked = true;
                  isAllGroup = isAllGroup + 1;
                }
              });
            } else {
              isAllGroup = isAllGroup + 1;
            }
          });
          if (isAllGroup === this.treeData.length) {
            this.checkAllState = true;
          } else {
            this.checkAllState = false;
          }
          this.treeData = JSON.parse(JSON.stringify(this.treeData));
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          console.log("debug log --> ", err);
          throw new Error("err", err);
        });
    },
    // 递归处理
    dataDeep(data) {
      data.map((item) => {
        item.title = item.categoryName;
        item.key = item.categoryId;
        item.children = item.permissionList;
        if (item.children && item.children.length > 0) {
          item.children.forEach((i) => {
            i.title = i.name;
            i.key = i.permissionId;
          });
        }
      });
      return data;
    },
    // 切换角色权限列表----
    selectChange(e) {
      this.roleOptions.forEach((item, index) => {
        if (item.id === e) {
          if (item.roleVOList) {
            item.roleVOList.forEach((item2, index2) => {
              if (item2.subjectType === "company") {
                this.actionId = item2.id;
              }
              if (item2.subjectType === "hr") {
                this.hrId = item2.id;
              }
            });
          }
        }
      });

      this.permissionList();
    },

    // 根据角色Id获取角色信息
    getRoleDetail(id) {
      roleDetailById(id)
        .then((res) => {
          this.roleInfos = res.data;
          this.roleName = this.roleInfos.name;
          this.roleIntro = this.roleInfos.description;
          this.roleId = this.roleInfos.id;
          this.roleType = this.roleInfos.type;
          this.getRolesList();
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          throw new Error(err);
        });
    },
    // 获取角色列表
    getRolesList() {
      getRoleList({ subjectType: this.subjectType, roleId: this.roleId })
        .then((res) => {
          this.roleOptions = res.data || [];
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          throw new Error(err);
        });
    },
    cancel() {
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep.ant-table .ant-table-row-indent + .ant-table-row-expand-icon {
  margin-right: 8px;
  position: relative;
  top: 24px;
}
.noIcon {
  padding-left: 50px;
}
.titleBox {
  display: flex;
  align-items: center;
  color: #595959;
  font-weight: 400;
  font-size: 14px;
  height: 54px;
  width: 100%;
  background: #fafafa;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #e8e8e8;
}
.childBox {
  display: flex;
  align-items: center;
  color: #595959;
  font-weight: 400;
  font-size: 14px;
  min-height: 54px;
  padding: 12px 0;
  width: 100%;
  background: #ffffff;
  border: 1px solid #e8e8e8;
  border-top: none;
}
.pConfig {
  padding: 0 24px;
  // width: 100%;
  .title {
    cursor: pointer;
    > strong {
      font-size: 20px;
    }
  }
}
</style>
